package com.spider.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spider.usercenter.common.ErrorCode;
import com.spider.usercenter.exception.BussinessException;
import com.spider.usercenter.mapper.UserMapper;
import com.spider.usercenter.model.domain.User;
import com.spider.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author AS笔墨白
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-08-03 21:30:56
*/
@Slf4j
@Service
  public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
  private static final String SALT = "spider";

  @Resource
  private UserMapper userMapper;

  @Override
  public long userRegister(String userAccount, String userPassword, String checkPassword,String planetCode) {
    if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword,planetCode)) {
      throw new BussinessException(ErrorCode.NULL_ERROR);
    }
    if (userAccount.length() < 4) {
      throw new BussinessException(ErrorCode.PARAMS_ERROR,"用户名过短");
    }
    if (userPassword.length() < 8 || checkPassword.length() < 8) {

      throw new BussinessException(ErrorCode.PARAMS_ERROR,"密码过短");
    }
    if(planetCode.length()>5){
      throw new BussinessException(ErrorCode.PARAMS_ERROR,"星球编号过长");
    }
    /**
     * 正则表达式校验用户名是否包含特殊字符
     */
    String validpattern = "[\\u00A0\\s\"`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
    Matcher matcher = Pattern.compile(validpattern).matcher(userAccount);
    if (matcher.find()) {
      throw new BussinessException(ErrorCode.PARAMS_ERROR,"含有特殊字符");
    }
    if (!userPassword.equals(checkPassword)) {
      throw new BussinessException(ErrorCode.PARAMS_ERROR,"两次密码输入不一致");
    }
    QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
    queryWrapper.eq("userAccount", userAccount);
     long count = this.count(queryWrapper);
    if (count > 0) {
      throw new BussinessException(ErrorCode.PARAMS_ERROR,"用户已经被注册过");
    }
     queryWrapper = new QueryWrapper<User>();
    queryWrapper.eq("planetCode",planetCode);
    count = this.count(queryWrapper);
    if (count > 0) {
      throw new BussinessException(ErrorCode.PARAMS_ERROR,"星球编号已经被注册过");
    }
    // 对密码进行加密
    final String SALT = "spider";
    String encryptPassword = DigestUtils.md5DigestAsHex((userPassword + "SALT").getBytes());
    User user = new User();
    user.setUseraccount(userAccount);
    user.setUserpassword(encryptPassword);
    user.setPlanetCode(planetCode);
    boolean save = this.save(user);
    if (!save) {
      return -1;
    }

    return user.getId();
  }

  @Override
  public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
    if (StringUtils.isAllBlank(userAccount, userPassword)) {
      throw new BussinessException(ErrorCode.NULL_ERROR);
    }
    if (userAccount.length() < 4) {
      throw new BussinessException(ErrorCode.PARAMS_ERROR,"用户名长度过短");
    }
    if (userPassword.length() < 8) {

      throw new BussinessException(ErrorCode.PARAMS_ERROR,"密码长度过短");
    }
    /**
     * 正则表达式校验用户名是否包含特殊字符
     */
    String validpattern = "[\\u00A0\\s\"`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
    Matcher matcher = Pattern.compile(validpattern).matcher(userAccount);
    if (matcher.find()) {
      throw new BussinessException(ErrorCode.PARAMS_ERROR,"包含特殊字符");
    }
    // 对密码进行加密

    String encryptPassword = DigestUtils.md5DigestAsHex((userPassword + "SALT").getBytes());
    QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
    queryWrapper.eq("userAccount", userAccount);
    queryWrapper.eq("userPassword", encryptPassword);
    User user = userMapper.selectOne(queryWrapper);
    if (user == null) {
      log.info("user login failed,userAccount cannot match userPassword");
      throw new BussinessException(ErrorCode.PARAMS_ERROR,"用户名或密码不一致");
    }
    User safetyUser = getSafetyUser(user);
    request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
    return safetyUser;
  }

  /**
   * 用户脱敏
   * @param oringinUser
   * @return
   */
  public User getSafetyUser(User oringinUser){
    if(oringinUser==null){
      return null;
    }
      User safetyUser = new User();
      safetyUser.setId(oringinUser.getId());
      safetyUser.setAvaturl(oringinUser.getAvaturl());
      safetyUser.setGender(oringinUser.getGender());
      safetyUser.setIsdelete(oringinUser.getIsdelete());
      safetyUser.setCaeatetime(oringinUser.getCaeatetime());
      safetyUser.setEmail(oringinUser.getEmail());
      safetyUser.setUserstatus(oringinUser.getUserstatus());
      safetyUser.setUpdatetime(oringinUser.getUpdatetime());
      safetyUser.setUseraccount(oringinUser.getUseraccount());
      safetyUser.setUsername(oringinUser.getUsername());
      safetyUser.setPhone(oringinUser.getPhone());
      safetyUser.setUserRole(oringinUser.getUserRole());
      safetyUser.setPlanetCode(oringinUser.getPlanetCode());
      return safetyUser;

  }

  @Override
  public int userLogout(HttpServletRequest request) {
    request.getSession().removeAttribute(USER_LOGIN_STATE);
    return 1;
  }
}





